﻿using cma.cimiss;
using iTelluro.Explorer.Infrastructure.CrossCutting.Logging;
using iTelluro.Explorer.Infrastructure.CrossCutting.NetFramework.Logging;
using MeteoInfoC.Data;
using MeteoInfoC.Data.MeteoData;
using MeteoInfoC.Global;
using MeteoInfoC.Layer;
using MeteoInfoC.Layout;
using MeteoInfoC.Legend;
using MeteoInfoC.Shape;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace SXMeteorological.Data.Utility
{
    public class WindRenderMap
    { //插值文件
        private string _interpolationDatFilePath;

        string _workDir = Application.StartupPath;
        //行政区划范围
        private double _xMin;
        private double _xMax;
        private double _yMin;
        private double _yMax;
        private string _featureName;
        private int _width;
        private int _height;
        private double left;
        private double top;

        //参数
        private Dictionary<string, string> _paraments = new Dictionary<string, string>();
        string _interfaceName = string.Empty;
        string _outputgrid = string.Empty;
        string _blnPath = string.Empty;
        string _tempDatFilePath = string.Empty;
        string _mapName = string.Empty;
        string _showCityNameDat = string.Empty;
        string _colorLevelPath = string.Empty;
        string _time = string.Empty;
        string _regionName = string.Empty;
        string _datfullpath = string.Empty;
        private readonly ILogger _logger;
        private string _isHourOrDay = string.Empty;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmin">经度</param>
        /// <param name="xmax">经度</param>
        /// <param name="ymin">纬度</param>
        /// <param name="ymax">纬度</param>
        /// <param name="para">接口参数</param>
        /// <param name="interfaceName">接口名</param>
        /// <param name="featureName">要素名称（生成图片放置的位置）</param>
        /// <param name="blnPath">行政区划bln全路径</param>
        /// <param name="mapName">出图的图名</param>
        /// <param name="showcityNameDat">显示各地区的中心点dat</param>
        /// <param name="colorpath">色标文件</param>
        public WindRenderMap(string regionName, string time, RegionPro pro, Dictionary<string, string> para, string interfaceName, string featureName, string mapName,  string hourOrday)
        {
            _logger = LoggerFrameFactory.CreateLog();
            _xMin = pro.XMin;
            _yMin = pro.YMin;
            _xMax = pro.XMax;
            _yMax = pro.YMax;
            _height = pro.Height;
            _width = pro.Width;
            left = pro.left;
            top = pro.top;
            _time = time;
            _regionName = regionName;
            _interfaceName = interfaceName;
            _featureName = featureName;
            _mapName = mapName;
            _paraments = para;
            _blnPath = pro.ShpPath;
            _showCityNameDat = pro.ShowCityNameDatPath;
            _isHourOrDay = hourOrday;
        }

        //获取要素数据 转成dat文件
        private string GetDatFileData(string interfaceId)
        {
            string datPath = string.Empty;
            try
            {
                InterfaceUse intF = new InterfaceUse();
                RetArray2D retArray2D = intF.QueryDataByInterface(_interfaceName, _paraments);
                if (retArray2D.data.Length == 0)
                {
                    _logger.LogInfo(_time + ":GetDatFileData查到的数据为0行" + ":" + _mapName);
                    return null;
                }
                string path = AppDomain.CurrentDomain.BaseDirectory;
                //临时目录
                var tempDir = Path.Combine(path, "temp");
                if (!Directory.Exists(tempDir))
                {
                    Directory.CreateDirectory(tempDir);
                }
                var guid = Guid.NewGuid().ToString();
                var currDir = Path.Combine(tempDir, guid);
               // Directory.CreateDirectory(currDir);
                _tempDatFilePath = currDir;

                System.IO.FileInfo fi = new System.IO.FileInfo(Path.Combine(currDir, "data.csv"));
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }
                FileStream fs = new FileStream(Path.Combine(currDir, "data.csv"), System.IO.FileMode.Create, System.IO.FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);

                sw.WriteLine(string.Join(",", "Site_Name", "Longitude", "Latitude", "VR", "VS"));
                if (retArray2D.data.Length != 0)
                {
                    for (var i = 1; i < retArray2D.data.Length; i++)
                    {
                        string[] s = retArray2D.data[i];
                        if (s[2] != "999999" && s[2] != "999998")
                        {
                            if (s[2] == "999990")
                                s[2] = "0";
                            sw.WriteLine(string.Join(",", s));
                        }
                    }
                }
                sw.Close();
                fs.Close();
                datPath = Path.Combine(currDir, "data.csv");
                _interpolationDatFilePath = Path.GetDirectoryName(datPath);
              
            }
            catch (Exception ex)
            {
                _logger.LogError(string.Format("GetDatFile{0}数据生成失败#{1}：{2}", _mapName, DateTime.Now, ex.Message));
            }
            return datPath;
        }

        public void TSMI_GrADSBarb()
        {
            //string datfullpath = GetDatFileData(_interfaceName);
            //_datfullpath = datfullpath;
            _datfullpath = @"D:\data\data.csv";
            string file = @"D:\RegionRending\" + _time.Remove(8, 6) + "000000" + @"\" + _featureName + @"\" + _regionName + @"\" + DateTime.Now.ToString("yyyyMMddHH") + "0000" + ".png";
            MeteoDataInfo aDataInfo = new MeteoDataInfo();
            aDataInfo.OpenLonLatData(_datfullpath);
            
            StationData stationData = aDataInfo.GetStationData("VR");
            StationData stationData1 = aDataInfo.GetStationData("VS");

            //插值
            GridDataSetting aGDP = new GridDataSetting();
            aGDP.DataExtent.minX = _xMin;
            aGDP.DataExtent.maxX = _xMax;
            aGDP.DataExtent.minY = _yMin;
            aGDP.DataExtent.maxY = _yMax;
            aGDP.XNum = 15;
            aGDP.YNum = 15;
            InterpolationSetting gridInterp = new InterpolationSetting();
            gridInterp.GridDataSet = aGDP;
            gridInterp.InterpolationMethod = InterpolationMethods.Cressman;
            gridInterp.Radius = 2;
            gridInterp.MinPointNum = 1;
            List<double> t = new List<double>();
            t.Add(10);
            t.Add(7);
            t.Add(4);
            t.Add(2);
            t.Add(1);
            gridInterp.RadList = t;
            double[] X = new double[1];
            double[] Y = new double[1];
            MeteoInfoC.Drawing.ContourDraw.CreateGridXY(gridInterp.GridDataSet, ref X, ref Y);
            double[,] S = stationData.Data;
            double[,] S1 = stationData1.Data;
            S = MeteoInfoC.Drawing.ContourDraw.FilterDiscreteData_Radius(S, gridInterp.Radius,
                gridInterp.GridDataSet.DataExtent, stationData.MissingValue);
            S1 = MeteoInfoC.Drawing.ContourDraw.FilterDiscreteData_Radius(S1, gridInterp.Radius,
                gridInterp.GridDataSet.DataExtent, stationData1.MissingValue);
            GridData ugridData = MeteoInfoC.Drawing.ContourDraw.InterpolateDiscreteData_Cressman(S,
                 X, Y, stationData.MissingValue, gridInterp.RadList);
            GridData vgridData = MeteoInfoC.Drawing.ContourDraw.InterpolateDiscreteData_Cressman(S1,
                 X, Y, stationData1.MissingValue, gridInterp.RadList);



            bool hasUndefData = false;
            LegendScheme aLS = LegendManage.CreateLegendSchemeFromGridData(vgridData, LegendType.UniqueValue, ShapeTypes.Point, ref hasUndefData);
            VectorLayer aLayer = DrawMeteoData.CreateGridBarbLayer(ugridData, vgridData, ugridData, aLS, false, "Barb_UV", true);          
            aLayer.IsMaskout = true;
            aLayer.Expanded = true;

            


            Extent u = new Extent();
            u.minX = _xMin;
            u.maxX = _xMax;
            u.maxY = _yMax;
            u.minY = _yMin;

            MeteoInfoC.Legend.LayersLegend layersLegend1 = new MeteoInfoC.Legend.LayersLegend();
            layersLegend1.ActiveMapFrame.AddLayer(aLayer);
            layersLegend1.ActiveMapFrame.MapView.ZoomToExtentEx(u);

            MapLayout mapLayout1 = new MapLayout();
            LayoutGraphic aTitle = mapLayout1.GetTexts()[0];
            aTitle.SetLabelText("陕西省极大风速的风向图");
            aTitle.Left = 140;
            aTitle.Top = 50;
            mapLayout1.ExportToPicture(file);
                         

        }

      
    }
}
